using SqlSugar;
using IM.Easy.Core.Services;
using IM.Easy.Core.Utils;
using IM.Easy.Infrastructure.Query;
using IM.Easy.Core.Extensions;
using IM.Easy.Entity.System;
using IM.Easy.CoreServices.Dto;
using IM.Easy.CoreServices.IServices;

namespace IM.Easy.CoreServices.Services
{
    public class AuthConfigService : AppServices<SysAuthConfig>, IAuthConfigService
    {

        public AuthConfigService(ISqlSugarClient db) : base(db)
        {

        }

        public SysAuthConfig Create(SysAuthConfig entity)
        {
            // TODO: 添加创建逻辑
            return Context.Insertable(entity).ExecuteReturnEntity();
        }

        public SysAuthConfig GetById(long id)
        {
            // TODO: 添加获取逻辑
            return Context.Queryable<SysAuthConfig>().InSingle(id);
        }

        public PageResponse<SysAuthConfig> GetPageList(SysAuthConfigQueryDto query)
        {
            var queryable = Context.Queryable<SysAuthConfig>();
            var exp = Expressionable.Create<SysAuthConfig>();
            exp = exp
                  .AndIF(!string.IsNullOrEmpty(query.ProviderName), s => s.ProviderName.Contains(query.ProviderName))
;
            var page = queryable
                 .Where(exp.ToExpression())
                 .ToPageList<SysAuthConfig, SysAuthConfig>(query);
            return page;
        }

        public bool Update(SysAuthConfig entity)
        {
            // TODO: 添加更新逻辑
            return Context.Updateable(entity).ExecuteCommandHasChange();
        }

        public bool Delete(params long[] Id)
        {
            // TODO: 添加删除逻辑
            return Context.Deleteable<SysAuthConfig>(Id).ExecuteCommandHasChange();
        }

        /// <summary>
        /// 根据标识符获取
        /// </summary>
        /// <param name="provider"></param>
        /// <returns></returns>
        public SysAuthConfig Get(string provider)
        {
            var config = base.GetFirst(s => string.Equals(s.Provider, provider, StringComparison.OrdinalIgnoreCase));
            if (config == null) ExceptionUtils.ThrowBusinessException($"未找到相关配置【{provider}】");
            if (!config.IsActive) ExceptionUtils.ThrowBusinessException($"未启用【{provider}】");
            return config;
        }
    }
}
